PHP solves the problem of Unix timestamp and date transfer based on DateTime class [for timestamps before 1970 and after 2038]

  • 2021-10-16 01:16:07
  • OfStack

In this paper, an example is given to explain how PHP solves the problem of Unix timestamp and date conversion based on DateTime class. Share it for your reference, as follows:

This problem mainly occurs in 32-bit systems, but does not exist in 64-bit systems. php 5.2 + provides the DateTime class to handle such problems, with the following reference scenario (note the handling of time zones):


//1 , Unix Time stamp to date 
function unixtime_to_date($unixtime, $timezone = 'PRC') {
  $datetime = new DateTime("@$unixtime"); //DateTime Class bug , join @ You can set the Unix The timestamp is passed in as a parameter 
  $datetime->setTimezone(new DateTimeZone($timezone));
  return $datetime->format("Y-m-d H:i:s");
}
//2 , date transfer Unix Time stamp 
function date_to_unixtime($date, $timezone = 'PRC') {
  $datetime= new DateTime($date, new DateTimeZone($timezone));
  return $datetime->format('U');
}
echo date_to_unixtime("1900-1-31 00:00:00"); // Output -2206425952
echo '<br>';
echo unixtime_to_date(date_to_unixtime("1900-1-31 00:00:00")); // Output 1900-01-31 00:00:00

PS: Here are some time and date related tools for your reference:

Online date/day calculator:
http://tools.ofstack.com/jisuanqi/date_jisuanqi

Online date calculator/difference days calculator:
http://tools.ofstack.com/jisuanqi/datecalc

Online Date-Day Difference Calculator:
http://tools.ofstack.com/jisuanqi/onlinedatejsq

Unix timestamp (timestamp) conversion tool:
http://tools.ofstack.com/code/unixtime

For more readers interested in PHP related content, please check the topics on this site: "Summary of php Date and Time Usage", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to php Object-Oriented Programming", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation" and "Summary of php Common Database Operation Skills"

I hope this article is helpful to everyone's PHP programming.


Related articles: